package Stack;

import java.util.Stack;

public class _735_AsteroidCollision {
    public int[] asteroidCollision(int[] asteroids) {
        Stack<Integer> stack = new Stack();
        for (int asteroid : asteroids) {
            if (!stack.isEmpty() && (asteroid >> 31 != stack.peek() >> 31) &&(stack.peek()>0 && asteroid<0)) {
                boolean bigger = false;
                while (!stack.isEmpty() && (asteroid >> 31 != stack.peek() >> 31) && (stack.peek()>0 && asteroid<0)) {
                    int num1 = Math.abs(stack.peek());
                    int num2 = Math.abs(asteroid);
                    if (num1 == num2) {
                        stack.pop();
                        bigger = false;
                        break;
                    } else if (num1 < num2) {
                        stack.pop();
                        bigger = true;
                    } else {
                        bigger = false;
                        break;
                    }
                }
                if (bigger) {
                    stack.push(asteroid);
                }
            } else {
                stack.push(asteroid);
            }
        }
        int[] res = new int[stack.size()];
        for (int i = res.length-1; i >=0; i--) {
            res[i] = stack.pop();
        }
        return res;
    }
}
